<?php

namespace SinoPHP\BbdBoss\Model;

use Upfor\UpforPHP\Model;

class AdminAuth extends Model {

    /**
     * 根据角色查询展示菜单列表
     *
     * @param  integer|array|null $nodeId
     * @return array
     */
    public function getDisplayMenusByNodeIds($nodeId = null) {
        $this->db->table('admin_auth_node')->where(['status' => 1, 'display' => 1, 'type' => ['menu', 'page']])->order('sort', 'ASC');

        if (!empty($nodeId) && (is_int($nodeId) || is_array($nodeId))) {
            $this->db->where('node_id', $nodeId);
        }

        return $this->db->getList();
    }

    /**
     * 获取权限列表信息
     *
     * @param  integer|array|null $nodeId
     * @return array
     */
    public function getPermissionsByByNodeIds($nodeId = null) {
        $this->db->table('admin_auth_node')->where(['status' => 1, 'type' => ['action', 'page']])->order('sort', 'ASC');

        $this->db->field(['node_id', 'title', 'controller', 'action', 'params', 'type', 'pid', 'sort', 'style']);

        if (!empty($nodeId) && (is_int($nodeId) || is_array($nodeId))) {
            $this->db->where('node_id', $nodeId);
        }

        return $this->db->getList();
    }

    /**
     * 获取用户角色列表
     *
     * @param  integer $userId
     * @return array
     */
    public function getUserRoleIds($userId = null) {
        $this->db->table('admin_auth_user_role');
        if ($userId) {
            $this->db->where('user_id', $userId);
        }

        return $this->db->column('role_id');
    }

    /**
     * 获取拥有权限节点列表
     *
     * @param  integer $userId
     * @return array
     */
    public function getUserNodes($userId = null) {
        $roleIds = $this->getUserRoleIds($userId);

        $this->db->table('admin_auth_role_node');
        if ($roleIds) {
            $this->db->where('role_id', $roleIds);
        }

        $nodeIds = $this->db->column('node_id');

        return array_unique($nodeIds);
    }

    /**
     * 获取所有权限节点ID
     */
    public function getAllNodeIds() {
        return $this->db->table('admin_auth_node')->where(['status' => 1])->order('sort', 'ASC')->column('node_id');
    }

    /**
     * 根据条件查询匹配的权限节点
     *
     * @param  array $condition
     * @return array
     */
    public function getMatchedNodes(array $condition) {
        $condition['status'] = 1;

        return $this->db->table('admin_auth_node')->where($condition)->getList();
    }

}
